from django.db import models
from django.contrib.auth.models import User
from article.models import ArticlePost
# django-ckeditor
from ckeditor.fields import RichTextField
# django-mptt
from mptt.models import MPTTModel, TreeForeignKey


# 博文的评论
class Comment(MPTTModel):
    article = models.ForeignKey(
        ArticlePost,
        verbose_name='文章标题',
        on_delete=models.CASCADE,
        related_name='comments'
    )
    user = models.ForeignKey(
        User,
        verbose_name='评论人',
        on_delete=models.CASCADE,
        related_name='comments'
    )
    # 富文本编辑
    body = RichTextField(
        verbose_name='评论内容'
    )
    created = models.DateTimeField(verbose_name='评论时间', auto_now_add=True)

    # mptt树形结构
    parent = TreeForeignKey(
        'self',
        verbose_name='父级评论',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='children'
    )

    # 记录二级评论回复给谁, str
    reply_to = models.ForeignKey(
        User,
        verbose_name='评论对象',
        null=True,
        blank=True,
        on_delete=models.CASCADE,
        related_name='replyers'
    )

    # 替换 Meta 为 MPTTMeta
    class MPTTMeta:
        order_insertion_by = ['created']

    def __str__(self):

        return self.body[:20]

    class Meta:
        verbose_name = '评论'
        verbose_name_plural = '评论'  # admin中显示
